<template>
  <view>
    <view class="home_detail">
      <uni-list @tap="gotodeviceContorl(online, equipmentNo, equipmentTypeId)">
        <uni-list-item
          title="设备编码"
          link
          :rightText="equipmentNo"
        ></uni-list-item>
        <uni-list-item
          title="设备名称"
          link
          :rightText="equipmentName"
        ></uni-list-item>
        <uni-list-item
          title="分类名称"
          link
          :rightText="equipmentTypeName"
        ></uni-list-item>
        <uni-list-item
          title="在线状态"
          link
          :rightText="online == 0 ? '离线' : '在线'"
        ></uni-list-item>
      </uni-list>
      <view class="home_user">设备成员</view>
    </view>
    <scroll-view
      scroll-y="true"
      :style="'height:' + clientHeight + 'px;'"
    >
      <uni-list
        v-for="(item, index) in userList"
        :key="index"
      >
        <uni-list-item
          :title="item.nickName"
          :note="item.phonenumber"
          showArrow
          :thumb="
            item.avatar == null || item.avatar == ''
              ? avatar
              : baseUrl + item.avatar
          "
          thumb-size="lg"
          :rightText="item.isadmin == 1 ? '管理员' : ''"
          @tap="setStoreUser(item.equipmentStoreNo, item.isadmin, item.userId)"
        ></uni-list-item>
      </uni-list>
    </scroll-view>
    <view
      class="btn_baocun"
      style="margin-top: 10rpx; min-height: 90rpx"
    >
      <button
        type="warn"
        v-if="isSharer == 0"
        @tap="exitShare"
        style="
          width: 80%;
          background-color: #ff976a;
          height: 80rpx;
          line-height: 80rpx;
        "
      >
        退出设备共享
      </button>
    </view>
  </view>
</template>

<script>
  import {
    getEquipment,
    delEquipment,
  } from '@/api/system/equiment/equipment.js'
  import {
    getStoreShareUsers,
    setAdmin,
    delShareRecord,
    setIsAdmin,
  } from '@/api/system/store/shareRecord.js'
  import config from '@/config'
  import { listConfig } from '@/api/system/config/config.js'
  export default {
    data() {
      return {
        equipmentName: '',
        equipmentNo: '',
        equipmentTypeName: '',
        equipmentTypeId: '',
        online: 0,
        isAdmin: false,
        userId: uni.getStorageSync('userId'),
        queryParams: {
          equipmentStoreNo: null,
          shareType: 0,
        },
        userList: [],
        clientHeight: 0,
        baseUrl: config.baseUrl,
        isSharer: null,
        avatar:
          'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
      }
    },
    onLoad(option) {
      this.equipmentNo = option.equipmentNo
      this.isSharer = option.isSharer
      if (option.type == 1) {
        this.isAdmin = true
        uni.setNavigationBarTitle({
          title: '我的共享设备详细', // 新标题
        })
      } else {
        this.isAdmin = false
        uni.setNavigationBarTitle({
          title: '我收到的共享设备详细', // 新标题
        })
      }
      //查询设备详细
      this.getEquipmentDetaile()
      //查询分享用户
      this.getShareUser()
    },
    onShow() {
      var that = this
      uni.getSystemInfo({
        success: function (res) {
          let screenHeight = uni.getSystemInfoSync().windowHeight //获取屏幕高度
          // 通过query 获取其余盒子的高度
          let query = uni.createSelectorQuery().in(that)
          query.select('.home_detail').boundingClientRect()
          query.select('.btn_baocun').boundingClientRect()
          //通过query.exec返回的数组 进行减法 同时 去除margin 和border的
          query.exec((res) => {
            let h1 = res[0].height
            let h2 = res[1].height
            let scrollHeight = screenHeight - h1 - h2 - 65
            that.clientHeight = scrollHeight
          })
        },
      })
    },
    methods: {
      //查询们的详细
      getEquipmentDetaile() {
        getEquipment(this.equipmentNo).then((response) => {
          if (response.code == 200) {
            this.equipmentName = response.data.equipmentName
            this.equipmentTypeName =
              response.data.mkEquipmentType == ''
                ? ''
                : response.data.mkEquipmentType.equipmentTypeName
            this.online = response.data.online
            this.equipmentTypeId = response.data.equipmentTypeId
          }
        })
      },
      //查询分享的设备成员包括自己
      getShareUser() {
        this.queryParams.equipmentStoreNo = this.equipmentNo
        getStoreShareUsers(this.queryParams).then((response) => {
          if (response.code == 200) {
            this.userList = response.rows
            uni.stopPullDownRefresh()
          }
        })
      },
      //跳转设备控制
      gotodeviceContorl: async function (online, equipmentNo, equipmentTypeId) {
        //将设备类型和设备号、是否此设备管理员存放缓存
        uni.setStorageSync('equipmentNo', equipmentNo)
        uni.setStorageSync('equipmentTypeId', equipmentTypeId)
        uni.setStorageSync('isAdmin', this.isAdmin)
        const configlist = await listConfig()
        if (configlist.wxConnectMQPrefix != '') {
          uni.setStorageSync(
            'subTopic',
            configlist.wxConnectMQPrefix +
              '.' +
              equipmentTypeId +
              '.' +
              equipmentNo
          )
        } else {
          uni.setStorageSync(
            'subTopic',
            'SERVER' + '.' + equipmentTypeId + '.' + equipmentNo
          )
        }
        if (online == 1) {
          switch (equipmentTypeId) {
            case '00000001':
              this.$tab.navigateTo('/controlpkg/index/index')
              break
            default: {
              this.$modal.msgError('暂无该类型界面')
            }
          }
        } else {
          this.$modal.msgError('设备已离线')
        }
      },
      //设置管理员或删除设备成员
      setStoreUser(equipmentStoreNo, isadmin, userId) {
        if (this.isSharer == 1) {
          if (userId != this.userId) {
            var thant = this
            uni.showActionSheet({
              alertText: '请选择',
              itemList: [
                isadmin == 1 ? '设置为普通成员' : '设置为管理员',
                '删除',
              ],
              success: (res) => {
                switch (res.tapIndex) {
                  case 0:
                    uni.showModal({
                      title: '提示',
                      content:
                        isadmin == 1
                          ? '确定设置该成员为普通成员吗？'
                          : '确定设置该成员为管理员吗？',
                      success: function (res) {
                        if (res.confirm) {
                          try {
                            const data = {
                              equipmentStoreNo: equipmentStoreNo,
                              isadmin: isadmin == 1 ? 0 : 1,
                              recipientId: userId,
                            }
                            setIsAdmin(data).then((response) => {
                              if (response.code == 200) {
                                uni.showToast({
                                  title: '设置成功',
                                  duration: 1500,
                                  success: function () {
                                    //查询设备成员
                                    thant.getShareUser()
                                  },
                                })
                              }
                            })
                          } catch (err) {
                            thant.$modal.msgError(err.msg)
                          }
                        }
                      },
                    })
                    break
                  case 1:
                    uni.showModal({
                      title: '提示',
                      content: '确定删除该设备成员吗？',
                      success: function (res) {
                        if (res.confirm) {
                          try {
                            const data = {
                              equipmentStoreNo: equipmentStoreNo,
                              recipientId: recipientId,
                            }
                            delShareRecord(data).then((response) => {
                              if (response.code == 200) {
                                uni.showToast({
                                  title: '删除成功',
                                  duration: 1500,
                                  success: function () {
                                    //查询设备成员
                                    thant.getShareUser()
                                  },
                                })
                              }
                            })
                          } catch (err) {
                            thant.$modal.msgError(err.msg)
                          }
                        }
                      },
                    })
                    break
                }
              },
              fail(error) {
                thant.$modal.msgError(error)
              },
            })
          } else {
            this.$modal.showToast('分享者本人不能设置和删除自己')
          }
        }
      },
      //退出分享门店
      exitShare() {
        var thant = this
        uni.showModal({
          title: '确定退出该分享设备吗？',
          content: '退出该分享的设备后将无法控制此设备',
          success: function (res) {
            if (res.confirm) {
              try {
                const data = {
                  equipmentStoreNo: thant.equipmentNo,
                  recipientId: thant.userId,
                }
                delShareRecord(data).then((response) => {
                  if (response.code == 200) {
                    uni.navigateBack({
                      delta: 1,
                      success: (res) => {
                        if ((res.errMsg = 'navigateBack:ok')) {
                          thant.$modal.msgSuccess('退出成功')
                        }
                      },
                    })
                  }
                })
              } catch (err) {
                thant.$modal.msgError(err.msg)
              }
            }
          },
        })
      },
    },
    //下拉刷新
    onPullDownRefresh() {
      this.getShareUser()
    },
  }
</script>

<style>
  page {
    background-color: #f9f9f9;
  }

  .home_detail {
    margin-top: 56rpx;
    width: 92%;
    margin: 56rpx auto;
  }

  ::v-deep .home_detail .uni-list-item__extra-text {
    font-size: 32rpx;
    overflow: hidden;
    text-align: right;
    vertical-align: middle;
    width: 300rpx;
  }

  .home_user {
    margin: 30rpx 0 30rpx 30rpx;
    font-size: 28rpx;
    color: #acacac;
  }
  .add_user {
    width: 80%;
    height: 80rpx;
    line-height: 80rpx;
  }
</style>
